<style lang="scss" scoped>
    .page {
        background: white;
        padding: 25px;

        ::v-deep .el-dialog {
            width: 80%;
            max-width: 500px;

            .el-dialog__body {
                padding: 10px 20px;
            }
        }
    }
</style>
<template>
    <div class="page">
        <el-row class="m-b-0">
            <el-button type="primary" size="medium" icon="el-icon-plus" @click="openDialog">添加角色
            </el-button>
        </el-row>
        <el-table
                v-loading="loading"
                :data="tableData.items"
                style="width: 100%;margin-bottom: 20px;"
                row-key="id">
            <el-table-column
                    prop="name"
                    label="角色名称">
            </el-table-column>
            <!-- <el-table-column
                prop="name"
                label="角色代码">
            </el-table-column> -->
            <el-table-column
                    label="系统角色">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.isStatic">是</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                    prop="isDefault"
                    label="是否默认">
                <template slot-scope="scope">
                    <el-tag type="success" v-if="scope.row.isDefault">是</el-tag>
                </template>
            </el-table-column>
            <el-table-column
                    prop="description"
                    label="角色描述">
            </el-table-column>
            <!--<el-table-column
                    prop="creationTime"
                    label="创建时间">
            </el-table-column>-->
            <el-table-column label="操作">
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            @click="handleEdit(scope.$index, scope.row)">编辑
                    </el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="_delete(scope.row)">删除
                    </el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination
                @size-change="(_size)=>{ filter.size = _size; getData()}"
                @current-change="(_page)=>{ filter.page = _page; getData()}"
                :current-page="filter.page"
                :page-sizes="defaultPageSize"
                :page-size="filter.size"
                layout="total, sizes, prev, pager, next, jumper"
                background
                :total="tableData.totalCount" style="margin-top: 20px;">
        </el-pagination>

        <el-dialog :title="editModel.id===0?'添加角色':'修改角色'" :visible.sync="dialogFormVisible" :close-on-click-modal="false" @closed="editLoading=false">

            <el-form :model="editModel" ref="editForm" :rules="rules" label-width="80px">
                <el-form-item label="角色名称" prop="name">
                    <el-input v-model="editModel.name" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="角色代码" prop="code">
                    <el-input v-model="editModel.code" placeholder="可以和角色名称相同" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="角色描述">
                    <el-input v-model="editModel.description" placeholder="角色说明、备注"
                              autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="默认角色">
                    <el-switch v-model="editModel.isDefault"></el-switch>
                    用户注册成功自动赋予此角色
                </el-form-item>
                <el-form-item label="权限" prop="permissions" style="margin-bottom: 0">
                    <!-- 如果你定义的权限只有一级权限（简化版），就直接用el-checkbox-group-->
                    <!--<el-checkbox-group v-model="editModel.permissions">
                        <el-checkbox :label="item.code" v-for="item in allPermissions">{{item.name}}</el-checkbox>
                    </el-checkbox-group>-->

                    <!--如果是细分权限，多级（含children）,就用tree-->
                    <el-tree
                        ref="permissionTree"
                        @check-change="checkChange"
                        :data="allPermissions"
                        show-checkbox
                        node-key="code"
                        :default-expand-all="true"
                        :default-checked-keys="editModel.permissions"
                        :props="{
                            children: 'children',
                            label: 'name'
                        }">
                    </el-tree>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="submitForm" :loading="editLoading">确 定
                </el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    let pagerHeader = {
        title: '角色管理',
        desc: '每个角色具有不同的权限，一个用户可以拥有多个角色。',
        breadcrumb: ['系统', '角色管理']
    }
    let modelStr = JSON.stringify({
        code: null,
        name: null,
        description: null,
        isStatic: false, // 系统自带角色，不能删除的
        isDefault:false,
        permissions: [],
        id: 0
    })
    export default {
        name: 'system_roles',
        data() {
            return {
                dialogFormVisible: false,
                activeName: '1',
                filter: {
                    page: 1,
                    size: 20,
                },
                editModel: JSON.parse(modelStr),
                rules: {
                    name: [
                        {required: true, message: '请输入角色代码', trigger: 'blur'},
                    ],
                    displayName: [
                        {required: true, message: '请输入角色名称', trigger: 'blur'},
                    ],
                    /*permissions: [
                        {required: true, message: '请配置权限', trigger: 'change'},
                        {
                            validator: (rule, value, callback) => {
                                console.log(value)
                                if (!value || value.length === 0) {
                                    callback(new Error('请配置权限'))
                                } else {
                                    callback()
                                }
                            }, trigger: 'change'
                        },
                    ]*/
                },
                loading: false,
                editLoading: false,

                allPermissions: [
                    /* 新手必读
                    》权限一般建议在后台程序中定义好，直接返回一个JSON数组给前端， 此处为了掩饰就直接定义在这里了。

                    》因为在开发时就已经确定了有哪些权限，所以无需存到数据库，那样做毫无意义。

                    》权限可以根据需求，设为简化版和细分版：
                    简化版只需要一个XX管理，根据是否具备权限来控制菜单是否显示即可，当然也可以在路由上或页面上做验证，这样就算你手动输入页面地址也是进不去的。
                    细分版可以更细的控制权限，精确到是否具有增、删、改、查、导入、下载等权限，可以精确控制有个按钮。
                    */

                    // 简化版：就只有一个文章管理，不细分添加、删除、修改、查看权限
                    {code: 'ArticleManage', name: '文章管理'},
                    {code: 'CategoryManage', name: '分类管理'},
                    {code: 'TagManage', name: '标签管理'},
                    //细分权限：
                    {
                        code: 'UserManage', //注意：实际验证的时候是验证children里面的，子权限，不是这个UserManage
                        name: '用户管理',
                        children: [
                            {code: 'UserManage.List', name: '查看'},
                            {code: 'UserManage.Create', name: '添加'},
                            {code: 'UserManage.Update', name: '修改'},
                            {code: 'UserManage.Delete', name: '删除'},
                        ]
                    },
                    {
                        code: 'RoleManage',
                        name: '角色权限',
                        children: [
                            {code: 'RoleManage.List', name: '查看'},
                            {code: 'RoleManage.Create', name: '添加'},
                            {code: 'RoleManage.Update', name: '修改'},
                            {code: 'RoleManage.Delete', name: '删除'},
                        ]
                    },
                ],
                tableData: {
                    items: [],
                    totalCount: 0
                },
            }
        },
        activated() {
             this.init();
        },
        created() {
            this.init();
        },
        methods: {
            init(){
                this.setPageHead(pagerHeader);
                //this.getPermissions(); //此处演示直接在前端写死了
                this.getData()
            },
            getData() {
                this.loading = true
                this.$apis.users.getRoles(this.filter).then(r => {
                    this.loading = false;
                    if (r.success)
                        this.tableData = r.result;
                    else
                        this.$msg.alert.error(r.error.message)
                }).catch(e => {
                    this.loading = false;
                })
            },
            // 分页结束

            getPermissions() {
                this.$apis.users.getAllPermissions().then(r => {
                    if (r.success) {
                        this.allPermissions = r.result.items;
                    } else
                        this.$msg.alert.error(r.error.message)
                }).catch(e => {
                })
            },
            checkChange() {
                this.editModel.permissions = this.$refs.permissionTree.getCheckedKeys();
            },
            openDialog() {
                if (this.editModel.id > 0) {
                    this.editModel = JSON.parse(modelStr);
                }
                this.dialogFormVisible = true;
                this.$nextTick(() => {
                    this.$refs.permissionTree.setCheckedKeys([]);
                    this.$refs.editForm.clearValidate();
                })
            },

            handleEdit(index, row) {
                /*
                this.loading = true;
                this.$apis.site.getRole(row.id).then(r => {
                    this.loading = false;
                    if (r.success) {
                        this.editModel = r.result;
                        this.dialogFormVisible = true;
                        this.$nextTick(() => {
                            this.$refs.editForm.clearValidate();
                        })
                    } else
                        this.$msg.alert.error(r.error.message)
                }).catch(e => {
                    this.loading = false;
                })*/

                // 修改一般是要从后台获取 修改页面需要的数据，这里演示就直接用当前行数据了
                this.editModel = {
                    code: row.code,
                    name: row.name,
                    description: row.description,
                    isStatic: row.isStatic, // 系统自带角色，不能删除的
                    isDefault:row.isDefault,
                    permissions: row.permissions,
                    id: row.id
                }
                this.dialogFormVisible = true;
                this.$nextTick(() => {
                    this.$refs.permissionTree.setCheckedKeys(row.permissions);
                    this.$refs.editForm.clearValidate();
                })
            },

            _delete(row) {
                this.$confirm('此操作将删除数据, 是否继续?', '', {
                    confirmButtonText: '是',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.getData()
                    this.$msg.notify.success('删除成功')
                    /*this.loading = true;
                    this.$apis.users.deleteRole(row.id).then(r => {
                        this.loading = false;
                        if (r.success) {
                            this.getData()
                            this.$msg.notify.success('删除成功')
                        } else {
                            this.$alert(r.error.message, '')
                        }
                    }).catch(e => {
                        this.loading = false;
                    })*/
                }).catch(e => {
                })
            },

            resetForm() {
                //this.$refs.permissionTree.setCheckedKeys([]);
                this.editModel = JSON.parse(modelStr);
            },

            submitForm() {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.editLoading = true;
                        this.$apis.users.saveRole(this.editModel).then(r => {
                            this.editLoading = false;
                            if (r.success) {
                                this.getData()
                                this.$msg.notify.success('成功', this.editModel.id === 0 ? '角色添加成功' : '角色修改成功')
                                if (this.editModel.id > 0) {
                                    //修改就自动关闭弹窗，添加就不关闭
                                    this.dialogFormVisible = false;
                                }
                                this.resetForm();
                            } else {
                                this.$msg.alert.error(r.error.message)
                            }
                        }).catch(e => {
                            this.editLoading = false;
                        })
                    }
                })
            },
        }
    }
</script>
